<?php

namespace app\service;

use app\common\BaseService;
use app\model\Contents as ContentsModel;

class ContentsService extends BaseService
{
  public static function getInstance(): ContentsService
  {
    return parent::getInstance();
  }

  public static function getModel(): ContentsModel
  {
    return ContentsModel::getInstance();
  }

  /*
   * 通过condition获取Contents
   */
  public function getContentsByCondition($conditions = [], $order = ['id' => 'desc']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    $result = $query->select()->toArray();
    return $result;
  }

  // 获取分类的所有子集
  public function getSubs($categorys, $catId = 0, $level = 1, $able = []){
    $subs = [];
    foreach($categorys as $item){
      if($item['fid'] === $catId && ($item['id'] === 0 || in_array($item['id'], $able))){
        $item['level'] = $level;
        $item['children'] = self::getSubs($categorys, $item['id'], $level + 1, $able);
        if ($item['children']) {
          $subs[] = [
            'id' => $item['id'],
            'fid' => $item['fid'],
            'is_show' => $item['is_show'],
            'contents_name' => $item['contents_name'],
            'route_path' => $item['route_path'],
            'route_name' => $item['route_name'],
            'level' => $item['level'],
            'children' => $item['children']
          ];
        } else {
          $subs[] = [
            'id' => $item['id'],
            'fid' => $item['fid'],
            'is_show' => $item['is_show'],
            'contents_name' => $item['contents_name'],
            'route_path' => $item['route_path'],
            'route_name' => $item['route_name'],
            'level' => $item['level']
          ];
        }
      }
    }
    return $subs;
  }
}